import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Input, Icon, message, Button, Form } from 'antd';
import styles from '../index.less';
import AuctionModal from '../../AuctionModal';
import CoverModal from '../../AuctionModal/CoverModal';

const FormItem = Form.Item;
const { TextArea } = Input;

@connect(state => ({

}))
@Form.create()

export default class BodyContent extends PureComponent {
  state = {
    title: '',
    itemTitle: '',
    itemDescription: '',
    items: [],
    titleRules: {},
    itemsRules: {},
    itemTitleRules: {},
    itemDescriptionRules: {},
    changeItemIndex: -1,
  }
  componentDidMount() {
    if (this.props.value.data) {
      this.handleSetFieldsValue(this.props.value.data);
    }
    const { moduleInfo } = this.props;
    const properties = moduleInfo.dataSchema.properties;
    const titleRules = properties.title;
    const itemsRules = properties.items;
    const itemTitleRules = properties.itemTitle;
    const itemDescriptionRules = properties.itemDescription;
    this.setState({
      titleRules, itemsRules, itemTitleRules, itemDescriptionRules
    });
  }
  componentWillReceiveProps(nextProps) {
    if (this.props.visible === false && nextProps.visible === true) {
      if (nextProps.value.data) {
        this.handleSetFieldsValue(nextProps.value.data);
      }
    } else if (this.props.visible === true && nextProps.visible === false) {
      this.setState({
        title: '',
        itemTitle: '',
        itemDescription: '',
        items: [],
      });
    }
  }
  
  handleSetFieldsValue = (data) => {
    if (data.title) {
      const fieldsValue = {
        title: data.title,
        itemTitle: data.itemTitle,
        itemDescription: data.itemDescription,
      };
      this.props.form.setFieldsValue(fieldsValue);
      if (this.props.value.data.items && this.props.value.data.items.length > 0) {
        const newItems = [];
        data.items.filter(item => newItems.push({ ...item, item_pic: item.item_pic }))
        this.setState({ ...fieldsValue, items: newItems });
      }
    } else {
      const fieldsValue = {
        title: this.state.title,
        itemTitle: this.state.itemTitle,
        itemDescription: this.state.itemDescription,
      };
      this.props.form.setFieldsValue(fieldsValue);
    }
  }
  handlePushContent = () => {
    const { itemsRules } = this.state;
    this.props.form.validateFieldsAndScroll(['title', 'itemTitle', 'itemDescription'], (err, val) => {
      if (!err) {
        if (this.state.items.length >= itemsRules.minItems) {
          if (this.props.onChange) this.props.onChange({
            title: val.title,
            itemTitle: val.itemTitle,
            itemDescription: val.itemDescription,
            items: this.state.items,
          });
        }
      }
    });
  }
  handleShowAuctionModal = () => {
    this.props.dispatch({
      type: 'auction/show',
      payload: { currentKey: `${this.props.name}_${this.props.index}` }
    });
  }
  handleAddItem = (auction) => {
    if (auction && auction.item) {
      const itemImages = [];
      auction.images.filter(item => itemImages.push({picUrl: item}));
      this.setState({
        items: [
          ...this.state.items,
          {
            item_title: auction.title,
            item_pic: auction.url,
            itemImages: itemImages,
            item_numiid: auction.resourceId,
            materialId: auction.materialId,
            itemPriceDTO: {
              "price": {
                "item_price": auction.item.finalPrice || auction.item.reservedPrice,
                "item_current_price": auction.item.finalPrice || auction.item.reservedPrice,
              }
            },
          }
        ]
      });
    }
  }
  handleEditItem = (auction, index) => {
    const newAuction = {
      title: auction.item_title,
      coverUrl: auction.item_pic,
      images: auction.itemImages.map(item => item = item.picUrl),
    }
    this.props.dispatch({
      type: 'album/showCover',
      payload: {
        auction: { ...newAuction },
        coverKey: `${this.props.name}_${this.props.index}`,
      }
    });
    this.setState({
      changeItemIndex: index,
    });
  }
  handleClearItem = (index) => {
    const newItems = this.state.items;
    newItems.splice(index, 1)
    this.setState({
      items: [ ...newItems ],
    });
  }
  handleChangeItemImg = (lastValue, image, title) => {
    const { changeItemIndex } = this.state;
    const newItems = Object.assign([], this.state.items);
    if (newItems[changeItemIndex]) {
      newItems[changeItemIndex].item_title = title;
      newItems[changeItemIndex].item_pic = image;
    }
    this.setState({
      items: newItems,
    });
  }
  render() {
    const { props, value, operation, form: { getFieldDecorator }, moduleInfo } = this.props;
    const { items, titleRules, itemsRules, itemTitleRules, itemDescriptionRules } = this.state;
    return (
      <div style={{ padding: '0 0 20px'}}>
        <div style={{marginBottom: 20}}>
          <p className={styles.lineTitleDefult} >
            {titleRules.title || ''}
          </p>
          <div className={styles.InputBox}>
            <FormItem>
                {getFieldDecorator('title', {
                  rules: [{
                    required: true, message: '不能为空',
                  }, {
                    min: titleRules.minLength, message: `输入内容长度不能小于${titleRules.minLength}`,
                  }, {
                    max: titleRules.maxLength, message: `输入内容长度不能大于${titleRules.maxLength}`,
                  }, {
                    whitespace: true, message: '内容不能为空格'
                  }],
                })(
                  <Input
                    maxLength={titleRules.maxLength ? titleRules.maxLength.toString() : '6'}
                    suffix={<span>{ this.props.form.getFieldValue('title') ? this.props.form.getFieldValue('title').length : 0 }/{titleRules.maxLength}</span>}
                    placeholder={titleRules['ui:placeholder']}
                  />
                )}
            </FormItem>
          </div>
        </div>
        <div style={{ marginBottom: 10 }}>
          { (!items || items.length < itemsRules.maxItems) &&
            <label onClick={() => this.handleShowAuctionModal()}>
              <div className={styles.upCover} style={{ width: 130, height: 130, paddingTop: 30 }}>
                <Icon type="plus" className={styles.uploadIcon} />
                <p>添加宝贝</p>
              </div>
            </label>
          }
          { items && items.length > 0 && items.map((item, index) =>
            <div key={index} className={styles.imgShowBox} style={{ width: 130, height: 130, lineHeight: '126px' }}>
              <img src={item.item_pic} style={{ maxWidth: '100%', maxHeight: '100%', height: 'auto', width: 'auto' }} />
              <div className={styles.clearImg}>
                <div onClick={() => this.handleEditItem(item, index)}>
                  <Icon type="edit" />
                </div>
                <div onClick={() => this.handleClearItem(index)}>
                  <Icon type="delete" />
                </div>
              </div>
            </div>)
          }
          <p className={styles.promptTextRed}>{items.length < itemsRules.minItems ? `不能小于最小数量限制${itemsRules.minItems}` : ''}</p>
          <p className={styles.promptText}>请上传段落中展示的宝贝并对宝贝信息进行完善编辑</p>
        </div>
        <div style={{ marginBottom: 20 }}>
          <p className={styles.lineTitleDefult} >
            {itemTitleRules.title || ''}
          </p>
          <div className={styles.InputBox}>
            <FormItem>
                {getFieldDecorator('itemTitle', {
                  rules: [{
                    required: true, message: '不能为空',
                  }, {
                    min: itemTitleRules.minLength, message: `输入内容长度不能小于${itemTitleRules.minLength}`,
                  }, {
                    max: itemTitleRules.maxLength, message: `输入内容长度不能大于${itemTitleRules.maxLength}`,
                  }, {
                    whitespace: true, message: '内容不能为空格'
                  }],
                })(
                  <Input
                    maxLength={itemTitleRules.maxLength ? itemTitleRules.maxLength.toString() : '8'}
                    suffix={<span>{ this.props.form.getFieldValue('itemTitle') ? this.props.form.getFieldValue('itemTitle').length : 0 }/{itemTitleRules.maxLength}</span>}
                    placeholder={itemTitleRules['ui:placeholder']}
                  />
                )}
            </FormItem>
          </div>
        </div>
        <div>
          <p className={styles.lineTitleDefult}>
            <span>{itemDescriptionRules.title || ''}</span>
            <span style={{ marginLeft: 280 }}>{ this.props.form.getFieldValue('itemDescription') ? this.props.form.getFieldValue('itemDescription').length : 0 }/{itemDescriptionRules.maxLength}</span>
          </p>
          <div className={styles.textareaBox}>
            <FormItem>
              {getFieldDecorator('itemDescription', {
                rules: [{
                  required: true, message: '不能为空',
                }, {
                  min: itemDescriptionRules.minLength, message: `文字长度太短, 要求长度最少为${itemDescriptionRules.minLength}`,
                }, {
                  max: itemDescriptionRules.maxLength, message: `文字长度太长, 要求长度最多为${itemDescriptionRules.maxLength}`,
                }, {
                  whitespace: true, message: '内容不能为空格'
                }],
              })(
                <TextArea
                  maxLength={itemDescriptionRules.maxLength ? itemDescriptionRules.maxLength.toString() : '100'}
                  placeholder={itemDescriptionRules['ui:placeholder']}
                  autosize={{ minRows: 4, maxRows: 4 }}
                >
                </TextArea>
              )}
            </FormItem>
          </div>
        </div>
        <AuctionModal k={`${this.props.name}_${this.props.index}`} onOk={this.handleAddItem} activityId={props.activityId || 0} />
        <CoverModal k={`${this.props.name}_${this.props.index}`} onOk={this.handleChangeItemImg} />
        <div style={{ height: 40, marginTop: 20 }}>
          <Button onClick={this.handlePushContent} type="primary" style={{ float: 'right' }}>确定</Button>
        </div>
      </div>
    );
  }
}
